package com.huluspace.learnhub.service;

import com.huluspace.learnhub.dto.ContentForListDTO;
import com.huluspace.learnhub.dto.PageResult;
import com.huluspace.learnhub.model.Content;
import com.huluspace.learnhub.model.User;
import com.huluspace.learnhub.repository.ContentRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Optional;

@Service
public class ContentService {

  private final ContentRepository contentRepository;
  private final UserService userService;
  private final RedisTemplate<String, Object> redisTemplate;
  public ContentService(ContentRepository contentRepository, UserService userService, RedisTemplate<String, Object> redisTemplate) {
    this.contentRepository = contentRepository;
    this.userService = userService;
    this.redisTemplate = redisTemplate;
  }

  public PageResult<ContentForListDTO> getContents(int page, int pageSize, String type, String keyword) {
    Pageable pageable = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Direction.DESC, "isTop", "createdAt"));
    Page<Content> pageData;
    if (StringUtils.hasText(type) && StringUtils.hasText(keyword)) {
      pageData = contentRepository.findByTypeAndTitleContaining(type, keyword, pageable);
    } else if (StringUtils.hasText(type)) {
      pageData = contentRepository.findByType(type, pageable);
    } else {
      pageData = contentRepository.findAll(pageable);
    }
    List<ContentForListDTO> dtoList = pageData.stream().map(ContentForListDTO::fromEntity).toList();
    return new PageResult<ContentForListDTO>(pageData.getTotalElements(), dtoList, page, pageSize);
  }

  public void publishRaw(String rawText, String username){
    // 查找用户
    User user = userService.findByUsername(username)
        .orElseThrow(() -> new RuntimeException("用户不存在"));
    String title = "未命名内容";
    Content content = new Content();
    content.setAuthor(user);
    content.setTitle(title);
    content.setBody(rawText);
    content.setType("其他"); // 可改为默认值
    contentRepository.save(content);
    // 放入AI队列
    redisTemplate.opsForList().leftPush("ai-content-queue", content.getId());
  }

  public Optional<Content> getContentById(Long id) {
    return contentRepository.findById(id);
  }

}
